/**
 * 我的通知

 * @author 程文智
 */
package com.taxsystem.chengwenzhi.personal_notices;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.main.taxsystem.R;
import com.main.taxsystem.TableInfoSet.PersonalNoticesTableInfo;
import com.main.taxsystem.TaxSystemContentProvider;
import com.taxsystem.huangguangxing.login.LoginActivity;
import com.taxsystem.huangguangxing.login.LoginMassege;
import com.taxsystem.huangguangxing.login.User;
import com.taxsystem.tool.CommonOperations;
import com.taxsystem.tool.HttpUtil;

/**
 * 我的通知模块。<br>
 * 请传递 userId 信息，如：<br>
 * int userId = 1;<br>
 * Intent intent = new Intent();<br>
 * intent.putExtra("userId", userId);
 * 
 * @author 程文智
 */
@SuppressLint("NewApi")
public class PersonalNoticesActivity extends Activity implements
		LoaderManager.LoaderCallbacks<Cursor> {
	private static final String TAG = "PersonalNoticesActivity";
	public final static String ACTION = "com.taxsystem.chengwenzhi.personal_notices.HTTP_GET_RESPONSE";
	private String HOST = null;
	private String url = null;
	private List<HashMap<String, String>> list = null;
	private ListView listView = null;
	private TextView emptyHintView = null;
	private ProgressBar loadingIcon = null;
	private int userId = -1;
	private LocalBroadcastManager lbm = null;
	private Thread myThread = null;
	private Cursor DBCursor = null;
	private CursorAdapter adapter = null;
	private Handler handler = null;
	private static final int NETWORK_CONNECT_FAIL = 1;
	private static final int HTTP_OK = 200;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//判断是否登录
		if(!LoginMassege.isLogin()){
			Log.v(TAG,"onCreate():do not login");
			Intent intent = new Intent(PersonalNoticesActivity.this,LoginActivity.class);
			startActivity(intent);
			this.finish();return;
		}
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.personal_notices);
		setProgressBarIndeterminateVisibility(true);//show ProgressBar on ActionBar
		init();
		getLoaderManager().restartLoader(0, null, this);
		HOST = getResources().getString(R.string.host);
		User user = LoginMassege.getUser();
		userId =user.getUserId();
		//TODO:测试
		userId = 2;
		url = HOST + "/notation/mylist?" + "userid=" + userId+"&startpos=1&count=20";
		adapter = new PersonalNoticeAdapter(this, DBCursor, true);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnPersonalNotationItemClickListener());
		handler = new MyHandler(PersonalNoticesActivity.this.getMainLooper());
		myThread = new GetNoticeFromInternetThread();
		myThread.start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.list_and_search, menu);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
            SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
            SearchView searchView = (SearchView) menu.findItem(R.id.searchView).getActionView();
            searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
            searchView.setIconifiedByDefault(false);
        }
        return true;
	}
	

	@Override
	protected void onStop() {
		if(myThread!=null && !myThread.isInterrupted())
			myThread.interrupt();
		super.onStop();
	}

	void init() {
		ActionBar bar = getActionBar();
		bar.setHomeButtonEnabled(true);
		bar.setIcon(R.drawable.actionbar_icon);
		bar.setDisplayHomeAsUpEnabled(true);
		bar.setBackgroundDrawable(new ColorDrawable(0xff34a4f7));

		listView = (ListView) this.findViewById(R.id.notations);
		emptyHintView = (TextView) this.findViewById(R.id.empty);
	}
	
	/**
	 * 当visibility为true，显示emptyHintView而隐藏listView
	 * 反之则隐藏emptyView，显示listView
	 * @param visibility 是否显示emptyHintView
	 */
	void setEmptyViewVisibility(boolean visibility){
		Log.v(TAG,"setEmptyViewVisibility():visibility="+visibility);
		if(visibility == true){
			listView.setVisibility(View.GONE);
			emptyHintView.setVisibility(View.VISIBLE);
		}else{
			listView.setVisibility(View.VISIBLE);
			emptyHintView.setVisibility(View.GONE);
		}
	}
	
	private void addIfNotExist(HashMap<String,String> newNotice){
		Log.v(TAG,"addIfNotExist()");
		
		String notationId = newNotice.get("notationId");
		String notationTitle = newNotice.get("notationTitle");
		String createTime = newNotice.get("createTime");
		String unread = newNotice.get("unread");
		
		ContentResolver cr  = getContentResolver();
		Cursor result = cr.query(TaxSystemContentProvider.URI_PERSIONAL_NOTICES, 
								new String[]{PersonalNoticesTableInfo.COLUMEN_NAME_NOTATION_ID},
								PersonalNoticesTableInfo.COLUMEN_NAME_NOTATION_ID+"='"+notationId+"'",
								null, null);
		if(result.getCount()>0){
			Log.v(TAG,"notice "+notationId + " is existed,"+result.toString());
			return;//the notice is existed, should not be inserted into database
		}
		
		ContentValues values = new ContentValues();
		values.put(PersonalNoticesTableInfo.COLUMEN_NAME_NOTATION_ID,notationId);
		values.put(PersonalNoticesTableInfo.COLUMEN_NAME_NOTATION_TITLE, notationTitle);
		values.put(PersonalNoticesTableInfo.COLUMEN_NAME_CREATE_TIME, createTime);
		values.put(PersonalNoticesTableInfo.COLUMEN_NAME_UNREAD, unread.equals("false")?false:true);
		
		Log.v(TAG,"addIfNotExist(): "+values.toString());
		cr.insert(TaxSystemContentProvider.URI_PERSIONAL_NOTICES, values);
	}
	
	private class OnPersonalNotationItemClickListener implements
			OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			String notationId = DBCursor.getString(DBCursor.getColumnIndex(
					PersonalNoticesTableInfo.COLUMEN_NAME_NOTATION_ID));
			Intent intent = new Intent(PersonalNoticesActivity.this,
					PersonalNoticeShowActivity.class);
			intent.putExtra(PersonalNoticesTableInfo.COLUMEN_NAME_NOTATION_ID, notationId);
			startActivity(intent);
		}
	}

	private class GetNoticeFromInternetThread extends Thread {
		private static final int MAX_REQUEST_TIME = 3;
		private boolean flag = true;
		@Override
		public void run() {
			if(!CommonOperations.isNetworkConnected(PersonalNoticesActivity.this))
				sendNetworkConnectFailMessage();
			
			String result = null;
			
			//发送3次网络请求均失败后停止
			for(int i=0;i<MAX_REQUEST_TIME;++i){
				Log.v(TAG,"GetNoticeFromInternetThread:"+(i+1)+"# 网络请求");
				try {
					HttpURLConnection conn =(HttpURLConnection) new URL(url).openConnection();
					try {
						InputStream in = new BufferedInputStream(
								conn.getInputStream());
						ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
				        byte[] data = new byte[255];  
				        int count = -1;  
				        while((count = in.read(data,0,255)) != -1)  
				            outStream.write(data, 0, count);  
				          
				        data = null;  
						result = new String(outStream.toByteArray(),"UTF-8");
					} finally {
						conn.disconnect();
					}
					
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if(result!=null)
					break;
			}
			Log.v(TAG, "get data from HttpUtil:" + result);
			if(null == result){
				sendNetworkConnectFailMessage();
				return;
			}else{
				Message msg = handler.obtainMessage();
				handler.sendEmptyMessage(HTTP_OK);
			}
			 parseJSON(result);
		}
		
		private void parseJSON(String JSONString){
			Log.v(TAG,"MyThread:parseJSON()");

			try {
				JSONObject jsonObject = new JSONObject(JSONString);
				JSONArray data = jsonObject.getJSONArray("data");
				for (int i = 0; i < data.length(); ++i) {
					JSONObject notation = data.getJSONObject(i);
					String notationId = notation.getString("notationId");
					String notationTitle = notation.getString("notationTitle");
					String createTime = notation.getString("createTime");
					String unread = notation.getString("unread");

					HashMap<String, String> map = new HashMap<String, String>();
					map.put("notationId", notationId);
					map.put("notationTitle", notationTitle);
					map.put("createTime", createTime);
					map.put("unread", unread.equals("true") ? "1" : "0");

					addIfNotExist(map);
					Log.v(TAG, "MyThread:parseJSON():add new notice:"+map.toString());
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} finally {
			}
		}
		
		private void sendNetworkConnectFailMessage(){
			Message msg = handler.obtainMessage();
			Bundle data = new Bundle();
			data.putInt("messageType",NETWORK_CONNECT_FAIL);
			msg.setData(data);
			handler.sendMessage(msg);
		}
	}

	private class MyHandler extends Handler{
		public MyHandler(Looper looper){
			super(looper);
		}
		
		
		@Override
		public void handleMessage(Message msg) {
			Log.v(TAG,"MyHandler:handleMessage()");
			Bundle b = msg.getData();
			switch(b.getInt("messageType")){
			case NETWORK_CONNECT_FAIL:{
				Toast.makeText(PersonalNoticesActivity.this,
						getResources().getString(R.string.network_connect_fail_hint), 
						Toast.LENGTH_SHORT).show();
				break;
			}
			}
			PersonalNoticesActivity.this.setProgressBarIndeterminateVisibility(false);
			//如果之前由于数据为空显示emptyHintView，那么现在判断数据是否更新
			if(DBCursor!=null && DBCursor.getCount()>0)
				setEmptyViewVisibility(false);
		}
	}
	
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		Log.v(TAG, "onCreateLoader() begin ,");
		CursorLoader loader = new CursorLoader(this,
				TaxSystemContentProvider.URI_PERSIONAL_NOTICES, null, null,
				null, null);
		return loader;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		if (cursor.getCount() < 1) {
			setEmptyViewVisibility(true);
			Log.v(TAG, "onCreateLoader() cursor.getCount() < 1, return");
			return;
		}
		DBCursor = cursor;
		cursor.setNotificationUri(getContentResolver(), TaxSystemContentProvider.URI_PERSIONAL_NOTICES);
		adapter.swapCursor(cursor);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		adapter.swapCursor(null);
	}
}
